package com.netease.ticket;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
 * 
 * @author bjyangfan
 * 预订
 */
public class OrderRequestSubmit {
	private String station_train_code;
	private String train_date;
	private String seattype_num;
	private String from_station_telecode;
	private String to_station_telecode;
	private String include_student = "00"; //成人票00，学生票是0X00
	private String from_station_telecode_name;
	private String to_station_telecode_name;
	private String round_train_date;
	private String round_start_time_str = "00:00--24:00";
	private String single_round_type = "1"; //单程
	private String train_pass_type = "QB"; //这个应该是“全部”的拼音缩写,另外两个值是GL（过路）和SF（始发）
	private String train_class_arr = "QB#D#Z#T#K#QT#";
	private String start_time_str = "00:00--24:00";
	private String train_start_time;
	private String arrive_time;
	private String from_station_name;
	private String to_station_name;
	private String from_station_no;
	private String to_station_no;
	private String ypInfoDetail;
	private String mmStr;
	private String locationCode;
	private String lishi;
	private String trainno4;
	
	private String url = "http://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=submutOrderRequest";
	private String queryJsUrl = "http://dynamic.12306.cn/otsweb/dynamicJsAction.do?jsversion=";
	private String queryInitUrl = "http://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
	
	public String cookie = null;
	public HttpClient client = null;
	public TrainInfo ti;
	public NameValuePair jsResult;
	
	public String user;
	public String jsFile;
	public String jsFileRaw;
	
	/**
	 * @param args ti 列车信息
	 */
	
	public OrderRequestSubmit()
	{
		//生成1000-9999之间的随机数
		int rand10000 = (int)(Math.random() * 9000 + 1000);
		queryJsUrl += String.valueOf(rand10000) + "&method=queryJs";
	}
	
	public void copyInfo(TrainInfo ti)
	{
		if(ti == null)
		{
			System.out.println("null TrainInfo!");
			return;
		}
		station_train_code = ti.station_train_code;
		train_date = ti.train_date;
		round_train_date = ti.round_train_date;
		seattype_num= ti.seattype_num;
		from_station_telecode = ti.from_station_telecode;
		to_station_telecode = ti.to_station_telecode;
		from_station_telecode_name = ti.from_station_telecode_name;
		to_station_telecode_name = ti.to_station_telecode_name;
		start_time_str = ti.start_time_str;
		train_start_time = ti.train_start_time;
		arrive_time = ti.arrive_time;
		from_station_name = ti.from_station_name;
		to_station_name = ti.to_station_name;
		from_station_no = ti.from_station_no;
		to_station_no = ti.to_station_no;
		ypInfoDetail = ti.ypInfoDetail;
		mmStr = ti.mmStr;
		locationCode = ti.locationCode;
		lishi = ti.lishi;
		trainno4 = ti.trainno4;
		
	}

	/**
	 * 预订
	 * @throws Exception
	 */
	public void preSubmit() throws Exception
	{
		if(client == null) client = new HttpClient();
		
		PostMethod method = this.getMethod();
	
		 
		 //将的cookie加入
		 Util.setReqHeader(method, queryInitUrl, this.cookie);
		 
		 int code = client.executeMethod(method);
		 
		 Header location = null;
		 
		 //这里会有重定向
		 if (code == HttpStatus.SC_MOVED_PERMANENTLY
	    		 || code == HttpStatus.SC_MOVED_TEMPORARILY
	    		 || code == HttpStatus.SC_SEE_OTHER
	    		 || code == HttpStatus.SC_TEMPORARY_REDIRECT) 
	     {
	    	 location = method.getResponseHeader("location");

	    	 System.out.println(location.getValue());
	    	 if(location != null){
		    	 String newUrl = location.getValue();
		    	 
		    	 //正常情况下应该是这个网址
		    	 if(!newUrl.equals("http://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init"))
		    	 {
		    		 System.out.println("maybe something wrong here:");
		    		 newUrl = "http://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
		    	 }

		    	 if(newUrl == null || newUrl.equals(""))newUrl = "/";
		    	 else
		    	 {
		    		 HttpMethod newMethod = new GetMethod(newUrl);
		    		 Util.setReqHeader(newMethod, queryInitUrl, this.cookie);
			    	 client.executeMethod(newMethod);
			    	 System.out.println("Redirect to: " + newUrl+",result:" + newMethod.getStatusLine().toString());
			    	 
			    	 //System.out.println(method.getResponseBodyAsString());
		    	 }
	    	 }
	     }
	}
	
	public PostMethod getMethod() throws Exception
	{
		//优先从网站获取
		HttpMethod method = new GetMethod(queryJsUrl);
		
		Util.setReqHeader(method, queryInitUrl, cookie);
		if(client.executeMethod(method) == 200)
		{
			String content = method.getResponseBodyAsString();
			content = content.replace("aj();", "");
			jsResult = Util.getJsResult(user + jsFile, content);
			Util.writeFile(user + jsFileRaw, content);
		}
		else//这里可能返回304
		{
			//从文件获取
			String content = Util.readFile(user + jsFileRaw, "UTF-8");
			jsResult = Util.getJsResult(user + jsFile, content);
		}
		
		NameValuePair[] param = { 
			new NameValuePair("station_train_code",station_train_code),  
            new NameValuePair("train_date",train_date),
            new NameValuePair("seattype_num",seattype_num),
            new NameValuePair("from_station_telecode",from_station_telecode),
            new NameValuePair("to_station_telecode",to_station_telecode),  
            new NameValuePair("include_student",include_student),  
            new NameValuePair("from_station_telecode_name",from_station_telecode_name),
            new NameValuePair("to_station_telecode_name",to_station_telecode_name),  
            new NameValuePair("round_train_date",round_train_date),
			new NameValuePair("round_start_time_str",round_start_time_str),  
	        new NameValuePair("single_round_type",single_round_type),  
	        new NameValuePair("train_pass_type",train_pass_type),  
	        new NameValuePair("train_class_arr",train_class_arr),
	        new NameValuePair("start_time_str",start_time_str),  
	        new NameValuePair("lishi",lishi),
	        new NameValuePair("train_start_time",train_start_time),  
	        new NameValuePair("trainno4",trainno4),
	        new NameValuePair("arrive_time",arrive_time),
	        new NameValuePair("from_station_name",from_station_name),  
	        new NameValuePair("to_station_name",to_station_name),
			new NameValuePair("from_station_no",from_station_no),  
	        new NameValuePair("to_station_no",to_station_no),  
	        //new NameValuePair("refundFlag","Y"), 
	        new NameValuePair("ypInfoDetail",ypInfoDetail),
	        new NameValuePair("mmStr",mmStr),  
	        new NameValuePair("locationCode",locationCode),
			jsResult,
			new NameValuePair("myversion","undefined")
   	 	} ;
		
		PostMethod postMethod = new PostMethod(this.url);
		
		postMethod.setRequestBody(param);
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		return postMethod;
	}

}
